package com.lenovo.server.weixin;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import com.lenovo.server.weixin.ExecuteCmd.Cmd;
import com.lenovo.server.weixin.response.TextMessage;
import com.lenovo.server.weixin.util.ContextUtil;
import com.lenovo.server.weixin.util.MessageUtil;

/**
 * 核心服务类
 * 
 */

public class CoreService

{
	static Logger mLog = Logger.getLogger("CoreService");
	private static HttpServletRequest request;

	/**
	 * 处理微信发来的请求
	 * 
	 * @param request
	 * @return
	 */

	public static String processRequest(HttpServletRequest request) {
		CoreService.request = request;
		String respMessage = null;
		try {
			// 默认返回的文本消息内容
			String respContent = "请求处理异常,请稍候尝试!";
			// xml请求解析
			Map<String, String> requestMap = MessageUtil.parseXml(request);
			// 发送方帐号(open_id)
			String fromUserName = requestMap.get("FromUserName");
			// 公众帐号
			String toUserName = requestMap.get("ToUserName");
			String createTime = requestMap.get("CreateTime");
			// 消息类型
			String msgType = requestMap.get("MsgType");
			String content = requestMap.get("Content");

			String log = "fromUserName " + fromUserName + " toUserName "
					+ toUserName + " createTime " + createTime + " content "
					+ content + " msgType " + msgType;
			slog.p(log);

			slog.p("now response the message to weixin server ");
			// 回复文本消息
			TextMessage textMessage = new TextMessage();
			textMessage.setToUserName(fromUserName);
			textMessage.setFromUserName(toUserName);
			textMessage.setCreateTime(new Date().getTime());
			textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
			// 文本消息
			if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
				respContent = "您发送的是文本消息!";
			}

			// 图片消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
				respContent = "您发送的是图片消息!";
			}

			// 地理位置消息

			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
				respContent = "您发送的是地理位置消息!";
			}

			// 链接消息
			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
				respContent = "您发送的是链接消息!";

			}

			// 音频消息

			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
				respContent = "您发送的是音频消息!";
			}

			// 事件推送

			else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {

				// 事件类型
				String eventType = requestMap.get("Event");

				// 订阅

				if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE))

				{
					respContent = "谢谢您的关注!";
					textMessage.setContent(respContent);
				}

				// 取消订阅

				else if (eventType.equals(MessageUtil.EVENT_TYPE_UNSUBSCRIBE)) {

					// TODO 取消订阅后用户再收不到公众号发送的消息,因此不需要回复消息
				}

				// 自定义菜单点击事件

				else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {

					// TODO 自定义菜单权没有开放,暂不处理该类消息
				}
			}

			textMessage.setContent(dealTextCmd(content));
			slog.p("befor parse xml msg " + respMessage);
			respMessage = MessageUtil.textMessageToXml(textMessage);
			slog.p("get the xml msg " + respMessage);
		} catch (Exception e) {
			e.printStackTrace();
			slog.p("Error processRequest " + e);
		}

		return respMessage;
	}

	/**
	 * 处理文本命令，并且返回相应的回应
	 * @param cmdCode
	 * @return
	 */
	private static String dealTextCmd(String cmdCode) {
		String responseMsg = "Server Error";
		try {
			Cmd cmd = Cmd.values()[Integer.parseInt(cmdCode)];
			switch (cmd) {
			case go_Lottery:
			case login:
			case register:
			case show_selfinfo:
				responseMsg = cmd.message + "正在开发中...";
				break;
			}
		} catch (Exception e) {
			// main menu
			responseMsg = getMainMenu();
		}
		return responseMsg;
	}

	private static String getMainMenu() {
		StringBuffer sb = new StringBuffer();
		Cmd[] arrays = Cmd.values();
		sb.append("主菜单");
		for (int i = 0; i < arrays.length; i++) {
			sb.append("\n");
			sb.append(i + ":" + wrapUrl(arrays, i));

		}
		return sb.toString();
	}

	private static String wrapUrl(Cmd[] arrays, int i) {
		if(arrays[i] == Cmd.register){
			//包装一个URL
			StringBuilder sb = new StringBuilder();
			sb.append("<a href=\"")
			.append(ContextUtil.getServerPath(request) + "login.jsp")
			.append("\">")
			.append(arrays[i].message)
			.append("</a>");
			slog.p("url is " + sb.toString());
			return sb.toString();
		}
		return arrays[i].message;
	}
	
}